<template>
  <el-dialog
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="1000px"
    title="收款分账"
    @close="close"
  >
    <el-form
      ref="formRef"
      :model="formData"
      size="small"
      :rules="formRules"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item
            label="付款方类型："
            style="width: 100%"
            :label-width="formLabelWidth"
          >
            <span>{{ getLabel('returned_money_type', rowData?.customerType) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="付款方名称："
            :label-width="formLabelWidth"
            style="width: 100%"
          >
            <span>{{ rowData?.customerName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="金额："
            :label-width="formLabelWidth"
            style="width: 100%"
          >
            <span class="flow-status-color">{{ moneyFormat(rowData?.receiveAmount) }}元</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="款项描述："
            :label-width="formLabelWidth"
            style="width: 100%"
          >
            <span>{{ rowData?.remark }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <item-title
            title="款项明细"
            prompt="*全部金额分账后方可提交*"
          >
            <template #btn>
              <el-button
                type="primary"
                @click="addRow"
              >增加行</el-button>
              <el-button
                type="primary"
                @click="clearAll"
              >全部删除</el-button>
            </template>
          </item-title>
        </el-col>
        <el-col :span="24">
          <el-alert
            v-if="tips"
            :title="tips"
            type="warning"
            style="margin-bottom: 10px;"
            show-icon
            :closable="false"
          />
          <el-table
            :data="formData.data"
            border
          >
            <el-table-column
              label="序号"
              header-align="center"
              align="center"
              prop="index"
              width="80px"
            >
              <template #default="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="款项类型"
              header-align="center"
            >
              <template #default="scope">
                <template v-if="scope.row.isComplete">
                  <el-form-item
                    :prop="'data.' + scope.$index + '.splitType'"
                    :rules="formRules.splitType"
                    style="margin: 14px 0px"
                  >
                    <span>{{ getLabel( 'payee_type', scope.row.splitType) }}</span>
                  </el-form-item>
                </template>

                <template v-else>
                  <el-form-item
                    :prop="'data.' + scope.$index + '.splitType'"
                    :rules="formRules.splitType"
                    style="margin: 14px 0px"
                  >
                    <el-select
                      v-model="scope.row.splitType"
                      placeholder="选择款项类型"
                      :disabled="rowData?.customerType==='agent'?false:true"
                    >
                      <template v-if="rowData?.customerType ==='agent'">
                        <el-option
                          v-for="(item, idx) in payeeTypeOption"
                          :key="item.id"
                          :label="item.label"
                          :value="item.value"
                        />
                      </template>
                      <template v-else>
                        <el-option
                          v-for="(item, idx) in payeeTypeOption.filter(p => p.value === 'goods_payment')"
                          :key="item.id"
                          :label="item.label"
                          :value="item.value"
                        />
                      </template>
                    </el-select>
                  </el-form-item>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              v-if="rowData?.customerType !=='agent'"
              label="款项来源"
              header-align="center"
            >
              <template #default="scope">
                <template v-if="scope.row.isComplete">
                  <el-form-item
                    :prop="'data.' + scope.$index + '.source'"
                    :rules="formRules.source"
                    style="margin: 14px 0px"
                  >
                    <span>{{ getLabel('payee_from', scope.row.source) }}</span>
                  </el-form-item>
                </template>
                <template v-else>
                  <el-form-item
                    :prop="'data.' + scope.$index + '.source'"
                    :rules="formRules.source"
                    style="margin: 14px 0px"
                  >
                    <el-select
                      v-model="scope.row.source"
                      placeholder="选择款项来源"
                      @change="(val) => payeeSourceChange(val,scope.$index)"
                    >
                      <el-option
                        v-for="(item, idx) in payeeFromOption.filter(p => p.value==='terminal_direct'||p.value==='agent_sale')"
                        :key="item.id"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              v-if="rowData?.customerType !=='agent'"
              label="回款方名称"
              header-align="center"
            >
              <template #default="scope">
                <template v-if="scope.row.isComplete||rowData?.customerType==='terminal'&&scope.row.source==='terminal_direct'">
                  <el-form-item
                    :prop="'data.' + scope.$index + '.returnCustomerId'"
                    :rules="formRules.returnCustomerId"
                    style="margin: 14px 0px"
                  >
                    <span>{{ scope.row.returnCustomerName }}</span>
                  </el-form-item>
                </template>
                <template v-else>
                  <el-form-item
                    :prop="'data.' + scope.$index + '.returnCustomerId'"
                    :rules="formRules.returnCustomerId"
                    style="margin: 14px 0px"
                  >
                    <el-select
                      v-model="scope.row.returnCustomerId"
                      style="width:100%"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入关键词搜索"
                      :remote-method="(keyword, cb) => customerQuerySearch(keyword, cb, scope.$index)"
                      :loading="customerLoading"
                      @change="(val) => handleCustomerSelect(val,scope.$index)"
                    >
                      <el-option
                        v-for="(item) in scope.row.customerOption"
                        :key="item.id"
                        :value="item.id"
                        :label="getCustomerLabel(item, scope.$index)"
                      >
                        <div class="productName">
                          <span v-if="scope.row.source ==='agent_sale'">{{ item.agentName }}</span>
                          <span v-if="scope.row.source ==='terminal_direct'">{{ item.terminalName }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              label="金额（元）"
              header-align="center"
            >
              <template #default="scope">
                <template v-if="scope.row.isComplete">
                  <el-form-item
                    :prop="'data.' + scope.$index + '.splitAmount'"
                    :rules="formRules.splitAmount"
                    style="margin: 14px 0px"
                  >
                    <span>{{ moneyFormat(scope.row.splitAmount) }}</span>
                  </el-form-item>
                </template>
                <template v-else>
                  <el-form-item
                    :prop="'data.' + scope.$index + '.splitAmount'"
                    :rules="formRules.splitAmount"
                    style="margin: 14px 0px"
                  >
                    <el-input
                      v-model="scope.row.splitAmount"
                      placeholder="请输入金额"
                      @input="scope.row.splitAmount=scope.row.splitAmount.replace(/^\.+|[^\d.]/g,'')"
                      @blur="splitAmountBlur(scope.row.splitAmount, scope.$index)"
                    />
                  </el-form-item>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              header-align="center"
            >
              <template #default="scope">
                <el-button
                  v-if="scope.row.isComplete"
                  type="text"
                  @click="rowEdit(scope.row)"
                >编辑</el-button>
                <el-button
                  v-else
                  type="text"
                  @click="rowComplete(scope.row, scope.$index)"
                >完成</el-button>
                <el-button
                  type="text"
                  @click="rowDelete(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  inject,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { crmStore } from '@CRM/store'

export default defineComponent({
  name: 'SplitMoney',
  emits: ['splitSuccess'],
  setup(props, context) {
    const api = inject('api')
    const formRef = ref(null)
    const currentInstance = getCurrentInstance()
    var datas = reactive({
      rowData: null,
      tips: '',
      formData: {
        id: 0,
        customerId: 0,
        customerType: '',
        customerName: '',
        customerNumber: '',
        data: [],
      },
      payeeTypeOption:
        crmStore.getters['dictionary/getDictionary']['payee_type'] || [],
      payeeFromOption:
        crmStore.getters['dictionary/getDictionary']['payee_from'] || [],
      customerLoading: false,
      customerOption: [],
      formRules: {
        splitType: [
          { required: true, message: '请选择款项类型', trigger: 'change' },
        ],
        source: [
          {
            required: true,
            message: '请选择款项来源',
            trigger: 'change',
          },
        ],
        returnCustomerId: [
          {
            required: true,
            message: '请选择回款方名称',
            trigger: 'change',
          },
        ],
        splitAmount: [
          {
            required: true,
            message: '请输入金额',
            trigger: 'blur',
          },
        ],
        normal: [],
      },
    })
    const splitAmountBlur = (splitAmount, index) => {
      if (splitAmount) {
        datas.formData.data[index].splitAmount = Number(splitAmount)
      } else {
        console.log('ddf')
      }
    }
    var formLabelWidth = ref(120)
    var dialogShow = ref(false)
    // 对部分表单字段进行校验
    const handleValidateField = (formRefs, val) => {
      console.log(val)
      return new Promise((resolve, reject) => {
        formRefs.validateField(val, (valid) => {
          if (!valid) {
            console.log(val)
            resolve()
          } else {
            console.log(val)
            reject()
            return false
          }
        })
      })
    }
    const open = (row) => {
      datas.rowData = row
      datas.formData.id = row.id
      datas.formData.customerId = row.customerId
      datas.formData.customerName = row.customerName
      datas.formData.customerNumber = row.customerNumber
      datas.formData.customerType = row.customerType
      datas.formData.data = []
      if (datas.rowData.customerType === 'agent') {
        datas.formRules.source[0].required = false
        datas.formRules.source[0].returnCustomerId = false
      }
      dialogShow.value = true
    }
    const close = () => {
      dialogShow.value = false
      formRef.value.resetFields()
    }
    const addRow = () => {
      var item = {
        splitType:
          datas.rowData.customerType === 'agent' ? '' : 'goods_payment',
        source: undefined,
        returnCustomerId: undefined,
        returnCustomerName: undefined,
        returnCustomerNumber: undefined,
        splitAmount: undefined,
        isComplete: false,
        customerLoading: false,
        customerOption: [],
      }
      datas.formData.data.push(item)
    }
    const clearAll = () => {
      datas.formData.data = []
    }
    const rowComplete = (row, index) => {
      var valArr = []
      if (datas.rowData.customerType === 'agent') {
        valArr = [
          handleValidateField(formRef.value, 'data.' + index + '.splitType'),
          handleValidateField(formRef.value, 'data.' + index + '.splitAmount'),
        ]
      } else {
        valArr = [
          handleValidateField(formRef.value, 'data.' + index + '.splitType'),
          handleValidateField(formRef.value, 'data.' + index + '.source'),
          handleValidateField(
            formRef.value,
            'data.' + index + '.returnCustomerId'
          ),
          handleValidateField(formRef.value, 'data.' + index + '.splitAmount'),
        ]
      }
      Promise.all(valArr).then(() => {
        row.isComplete = true
      })
    }
    const rowEdit = (row) => {
      row.isComplete = false
    }
    const rowDelete = (index) => {
      datas.formData.data.splice(index, 1)
    }
    const splitMoneyValidate = () => {
      var bool = true
      var splitTotal = 0
      datas.formData.data.forEach((item) => {
        splitTotal += item.splitAmount
      })
      if (splitTotal !== datas.rowData.receiveAmount) {
        bool = false
        datas.tips = '您的分账金额总和与你的收款金额不一致'
      } else {
        datas.tips = ''
      }
      return bool
    }
    const confirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          if (!splitMoneyValidate()) {
            return
          }
          api.internalControl
            .INTERNAL_CONTROL_FINANCE_SPLIT_CREATE(datas.formData)
            .then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '分账成功',
                })
                context.emit('splitSuccess')
                close()
              }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    const payeeSourceChange = (val, index) => {
      if (datas.rowData?.customerType === 'terminal') {
        if (datas.formData.data[index].source === 'terminal_direct') {
          datas.formData.data[index].returnCustomerId = datas.rowData.customerId
          datas.formData.data[index].returnCustomerName =
            datas.rowData.customerName
        } else {
          datas.formData.data[index].returnCustomerId = ''
          datas.formData.data[index].returnCustomerName = ''
        }
      }
    }
    const getCustomerLabel = (item, index) => {
      var label = ''
      if (datas.formData.data[index].source === 'agent_sale') {
        label = item?.agentName
      } else if (datas.formData.data[index].source === 'terminal_direct') {
        label = item?.terminalName
      }
      console.log(label)
      return label
    }
    const customerQuerySearch = async(queryString, cb, index) => {
      datas.formData.data[index].customerLoading = true
      const a = {
        id: datas.rowData?.customerId,
        customerType: datas.rowData?.customerType,
        source: datas.formData.data[index].source,
        keyWord: queryString,
      }
      let results = []
      const res = await api.common.DEV_AGENT_TERMINAL_SEARCH(a)
      if (res.code === 0) {
        datas.formData.data[index].customerLoading = false
        results = res.data || []
        datas.formData.data[index].customerOption = results
      }
    }

    const handleCustomerSelect = (val, index) => {
      var sel = datas.formData.data[index].customerOption.find(
        (p) => p.id === val
      )
      switch (datas.formData.data[index].source) {
        case 'agent_sale':
          datas.formData.data[index].returnCustomerName = sel.agentName
          break
        case 'terminal_direct':
          datas.formData.data[index].returnCustomerName = sel.terminalName
          break
      }
    }
    return {
      formRef,
      ...toRefs(datas),
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
      addRow,
      clearAll,
      rowComplete,
      rowEdit,
      rowDelete,
      customerQuerySearch,
      handleCustomerSelect,
      payeeSourceChange,
      splitAmountBlur,
      getCustomerLabel,
    }
  },
})
</script>
